package com.autumn.platform.auth.core.access.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;

import com.autumn.platform.auth.core.access.IAccessController;
import com.autumn.platform.auth.core.access.IPermission;
import com.autumn.platform.core.context.response.IResponse;
import com.autumn.platform.core.logger.Logs;

public class AccessControllerComposite implements IAccessController {

    @Autowired(required = false)
    private List<IAccessController> accessControllers;

    @Override
    public IResponse isPermitted(IPermission permission) throws Exception {
        IResponse first = null;
        List<IAccessController> accessControllers = getAccessControllers();
        if (null != accessControllers && !accessControllers.isEmpty()) {
            for (IAccessController accessController : accessControllers) {
                IResponse response = accessController.isPermitted(permission);
                if (null != response) {
                    if (response.isSuccess()) {// 只要一个成功就返回
                        Logs.debug("Success:AccessControllerComposite.isPermitted(" + permission.getPermId() + ":" + permission.getPermType() + ":" + permission.getPermTypeKey() + ")");
                        return response;
                    } else if (null == first) {//记录第一个失败的认证
                        first = response;
                    }
                }
            }
        }
        if (null != permission) {
            Logs.debug("Failure:AccessControllerComposite.isPermitted(" + permission.getPermId() + ":" + permission.getPermType() + ":" + permission.getPermTypeKey() + ")");
        }
        return first;
    }

    public List<IAccessController> getAccessControllers() {
        return accessControllers;
    }

    public void setAccessControllers(List<IAccessController> accessControllers) {
        this.accessControllers = accessControllers;
    }
}
